//
//  IGAlertVC.swift
//  ImGuider X
//
//  Created by 陆涛 on 2018/10/19.
//  Copyright © 2018 imguider. All rights reserved.
//

import UIKit

class IGAlertVC: UIAlertController {
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        // Do any additional setup after loading the view.
    }
    
    typealias block = (title:String,block:(() -> Void)? )
    
    
    class func show(title:String?,message:String?,
                    commit:block?) {

        self.show(title: title, message: message, commit: commit, force: false)
    }
    
    class func show(title:String?,message:String?,
                    commit:block?,force:Bool) {
        
        self.show(vc: nil, title: title, message: message, commit: commit, cancel: nil, force: force)
    }
    
    class func show(title:String?,message:String?,
                    commit:block?,cancel:block?) {
        
        self.show(vc: nil, title: title, message: message, commit: commit, cancel: cancel)
    }
    
    
    ///  给予vc或者取最上层viewcontroller直接显示 alert
    ///
    /// - Parameters:
    ///   - vc: 弹出alert的vc 如果不传 会自动获取最上层vc
    ///   - title: 标题
    ///   - message: 详情
    ///   - commit: 确定按钮
    ///   - cancel: 取消按钮
    ///   - force: 强制显示，不能取消
    class func show(vc:UIViewController?,
                    title:String?,message:String?,
                    commit:block?,cancel:block?,force:Bool = false) {
        
        let alertVC = IGAlertVC(title: title, message: message, preferredStyle: UIAlertController.Style.alert)
        
        if let block = commit {
            
            let action = UIAlertAction(title: block.title, style: .default) { _ in
                
                block.block?()
                if force {
                    superVC(vc)?.present(alertVC, animated: true, completion: nil)
                }
            }
            
            alertVC.addAction(action)
        }
        
        if let block = cancel {
            
            let action = UIAlertAction(title: block.title, style: .cancel) { _ in
                
                block.block?()
            }
            
            alertVC.addAction(action)
        }
        
        superVC(vc)?.present(alertVC, animated: true, completion: nil)
    }
    
    private class func superVC(_ vc:UIViewController?) -> UIViewController? {
        
        if let vc = vc {
            
            
            return vc
        }
        
        return Util.topViewController()
    }
}

